<template>
  <el-drawer
    :visible.sync="drawer"
    direction="rtl"
    size="50%"
    :with-header="false"
    :width="700"
  >
    <div class="drawer_box">
      <div class="drawer_title">
        <div class="drawer_t">
          <div class="drawer_t_l">
            <img
              class="drawer_t_l_img"
              src="../../../../../static/skin/herodoo/main/platform/home/img/piliangoumai.png"
              alt=""
            />
            {{ type == 1 ? "新增" : "修改"}}车辆信息
          </div>
          <img
            class="drawer_t_r"
            src="../../../../../static/skin/herodoo/main/platform/home/img/guanbi.png"
            alt=""
            @click="drawer = false"
          />
        </div>
      </div>
      <div class="drawer_content">
        <div class="title">车辆信息：</div>
        <div class="form-item">
          <div class="label">车牌号：</div>
          <input class="input" v-model="form.Code" placeholder="请输入车牌号" />
        </div>
        <div class="form-item">
          <div class="label">车辆品牌：</div>
          <el-select v-model="form.BrandID" placeholder="请选择车辆品牌" @change="changeBrand">
            <el-option v-for="item in BrandList" :key="item.ID" :label="item.Name" :value="item.KeyValue">
            </el-option>
          </el-select>
        </div>
        <div class="form-item">
          <div class="label">车系：</div>
          <el-select v-model="form.SystemID" placeholder="请选择车系" @change="changeSystem"
          :no-data-text="SystemList.length == 0 && form.BrandID ? '该品牌暂无车系' : '请先选择车辆品牌'">
            <el-option v-for="item in SystemList" :key="item.ID" :label="item.Name" :value="item.ID">
            </el-option>
          </el-select>
        </div>
        <div class="form-item">
          <div class="label">车型：</div>
          <el-select v-model="form.TypeID" placeholder="请选择车型" @change="changeType"
          :no-data-text="TypeList.length == 0 && form.SystemID ? '该车系暂无车型' : '请先选择车系'">
            <el-option v-for="item in TypeList" :key="item.ID" :label="item.Name" :value="item.ID">
            </el-option>
          </el-select>
        </div>
        <!-- <div class="form-item">
          <div class="label">说明：</div>
          <textarea class="textarea" v-model="form.desc" placeholder="请输入备注内容" ></textarea>
        </div> -->
        <div class="title">司机信息：</div>
        <div class="cat-info" v-for="(driverInfo, index) in driverList" :key="driverInfo.uuid">
          <div class="form-item" >
            <div class="label">
              <div class="delete-box" v-if="driverList.length > 1" @click="deleteDriver(driverInfo, index)"></div>
              司机{{index+1}}：
            </div>
            <SelectCat ref="selectCat" @getDriverId="getDriverId" :sign="driverInfo.uuid" :octopus="octopus" :driver="driverInfo.Driver"></SelectCat>
          </div>
        </div>

        <div class="form-item">
          <div class="label">添加司机信息：</div>
          <div class="add-driver" @click="handleAddFormDriver">
            <i class="el-icon-plus"></i>
            <span>点击添加司机</span>
          </div>
        </div>
        <div class="form-item">
          <div class="label">创建人：</div>
          <div class="desc">{{ form.CreateUserID }}</div>
        </div>
        <div class="form-item">
          <div class="label">创建日期：</div>
          <div class="desc">{{ form.CreateTime }}</div>
        </div>
      </div>
      <div class="drawer_footer">
        <button class="footer-btn" @click="handleUpdate">保存</button>  
      </div>
    </div>
  </el-drawer>
</template>

<script>
import SelectCat from './SelectCat.vue'
export default {
  name: "cat_dialog",
  components: {
    SelectCat
  },
  props: {
    type: {
      type: [String, Number],
      default: 1
    },
    messageList: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      octopus: this.$parent.octopus,
      drawer: false,
      hisList: [],
      tabID: 2,
      form: {},
      driverList: [],
      BrandList: [],
      SystemList: [],
      TypeList: [],
      ParentkeyValue: null,
    }
  },
  watch: {
    drawer(v) {
      if(v) {
        if(this.type == 2) {
          this.form = this.messageList
          this.getDriverList()
        } else {
          this.form = {
            Code: "",
            BrandID: "",
            SystemID: "",
            TypeID: "",
            desc: "",
          }
          this.driverList = [{
            uuid: new Date().getTime(),
            Driver: null,
            Mobile: '',
          }]
          this.hisList = []
        }
        this.getBrandList()
      }
    },
  },
  methods: {
    drawerOp() {
      this.drawer = true;
    },
    handleAddFormDriver() {
      let obj = {
        uuid: new Date().getTime(),
        Driver: '',
        Mobile: '',
      }
      this.driverList.push(obj);
    },
    getDriverList() {
      let o = this
      this.driverList = []
      this.octopus.request.api.post(
        "/Octopus/Engine/List",
        {
          id: 1232,
          cellData: [
            {name: "Code"},	// 车牌号
            {name: "Driver"},	// 司机
            {name: "ID"},	// ID
            {name: "Mobile"},	// 手机号
            {name: "Name"},	// 司机
          ],
          paramData: {
            CompanyID: this.octopus.passport.authorization.company == 1 ? "NULL" :this.octopus.passport.authorization.company,
            Code: this.form.Code,
            BrandID: "NULL",
            SystemID: "NULL",
            TypeID: "NULL",
            Driver: "NULL"
          }
        },
        function (data) {
          if (data.status.code == 200) {
            data.content.queryData.map(item => {
              o.driverList.push({
                catID: item.ID,
                uuid: new Date().getTime() + parseInt(Math.random() * 10000),
                Driver: item.Driver,
                Mobile: item.Mobile,
              })
            })
            o.hisList = JSON.parse(JSON.stringify(o.driverList))
          } else {
            o.octopus.tips.error(data);
          }
        })
    },

    deleteDriver(item, index) {
      this.driverList.splice(index, 1)
    },
    handleUpdate() {
      if(!this.form.Code.trim()) {
        this.$message.error('请输入车牌号')
        return
      }
      if(!this.form.BrandID) {
        this.$message.error('请选择车辆品牌')
        return
      }
      if(!this.form.SystemID) {
        this.$message.error('请选择车系')
        return
      }
      if(!this.form.TypeID) {
        this.$message.error('请选择车型')
        return
      }
      let queueList = [], addList = [], deleteList = [], updateList = [],count = 0
      if(this.hasDuplicates(this.driverList, "Driver")) {
        this.$message.error('选择的司机有重复，请重新选择')
        return
      }
      this.driverList.map((item, index) => {
        if(!item.Driver) {
          count++
          return
        }
      })
      if(count != 0) {
        this.$message.error("请选择司机")
        return
      }
      addList = this.driverList.filter(newItem => !this.hisList.some(oldItem => oldItem.Driver == newItem.Driver))
      deleteList = this.hisList.filter(oldItem => !this.driverList.some(newItem => newItem.Driver == oldItem.Driver))
      updateList = this.driverList.filter(newItem => this.hisList.some(oldItem => newItem.Driver == oldItem.Driver))

      if(addList.length) {
        addList.map(item => {
          queueList.push(this.catCreate(item))
        })
      }
      if(deleteList.length) {
        deleteList.map(item => {
          queueList.push(this.catDelete(item))
        })
      }
      if(updateList.length) {
        updateList.map(item => {
          queueList.push(this.catUpdate(item))
        })
      }
      Promise.all(queueList).then(res => {
        this.$message.success('更新成功')
        this.$emit('refresh')
        this.drawer = false
      })
    },
    getDriverId({ sign, id, data }) {
      const index = this.driverList.findIndex(item => item.uuid == sign)
      this.driverList.splice(index, 1, {
        catID: data.ID,
        uuid: this.driverList[index].uuid,
        Driver: id,
        Mobile: data.Mobile,
      })
    },
    // 新增司机
    catCreate(item) {
      return new Promise((resolve, reject)=> {
        let o = this
        this.octopus.request.api.post("/Octopus/Engine/Item", {
          id: 1212,
          type: "CREATE",
          cellData: [
            {name: "Code", defaultValue: this.form.Code},
            {name: "BrandID", defaultValue: this.form.BrandID},	// 车品牌
            {name: "SystemID", defaultValue: this.form.SystemID}, // 车系
            {name: "TypeID", defaultValue: this.form.TypeID},	// 车型
            {name: "CreateUserID", defaultValue: this.octopus.passport.id},	// 创建人
            {name: "CompanyID", defaultValue: this.octopus.passport.authorization.company},	// 车辆所属公司
            {name: "Driver", defaultValue: item.Driver},	// 司机
            {name: "Mobile", defaultValue: item.Mobile},	// 手机号
            {name: "UseCount", defaultValue: this.form.TypeID},	// 使用人数
          ]
        }, function(data) {
          if (data.status.code === 200) {
            resolve(data.content.queryData)
          } else {
            o.octopus.tips.error(data);
            reject(data)
          }
        })
      })      
    },

    // 删除司机
    catDelete(item) {
      return new Promise((resolve, reject)=> {
        let o = this
        this.octopus.request.api.post("/Octopus/Engine/Item", {
          id: 1212,
          type: "DELETE",
          value: item.catID
        }, function(data) {
          if (data.status.code === 200) {
            resolve(data.content.queryData)
          } else {
            o.octopus.tips.error(data);
            reject(data)
          }
        })
      })
    },
    // 更新司机
    catUpdate(item) {
      return new Promise((resolve, reject)=> {
        let o = this
        this.octopus.request.api.post("/Octopus/Engine/Item", {
          id: 1212,
          type: "UPDATE",
          value: item.catID,
          cellData: [
            {name: "Code", defaultValue: this.form.Code},
            {name: "BrandID", defaultValue: this.form.BrandID},	// 车品牌
            {name: "SystemID", defaultValue: this.form.SystemID}, // 车系
            {name: "TypeID", defaultValue: this.form.TypeID},	// 车型
            {name: "CreateUserID", defaultValue: this.octopus.passport.id},	// 创建人
            {name: "CompanyID", defaultValue: this.octopus.passport.authorization.company},	// 车辆所属公司
            {name: "Driver", defaultValue: item.Driver},	// 司机
            {name: "Mobile", defaultValue: item.Mobile},	// 手机号
            {name: "UseCount", defaultValue: this.form.TypeID},	// 使用人数
          ]
        }, function(data) {
          if (data.status.code === 200) {
            resolve(data.content.queryData)
          } else {
            o.octopus.tips.error(data);
            reject(data)
          }
        })
      })
    },

    changeBrand(val) {
      this.ParentkeyValue = this.BrandList.find(item => item.KeyValue == val).ID
      this.form.SystemID = null
      this.form.TypeID = null
      this.getSystemList()
    },
    changeSystem(val) {
      this.form.TypeID = null
      this.getTypeList()
    },
    changeType(val) {},
    // 获取车辆品牌
    getBrandList() {
      let o = this
      this.octopus.request.api.post("/Octopus/Engine/List", {
        id: 1233,
        cellData: [
          {name: "ID"},	// ID
          {name: "KeyValue"},	// KeyValue
          {name: "Name"},	// Name
          {name: "ParentkeyValue"},	// ParentkeyValue
        ]
      }, function(data) {
        if (data.status.code === 200) {
          o.BrandList = data.content.queryData
          if(o.form.BrandID) {
            o.ParentkeyValue = o.BrandList.find(item => item.KeyValue == o.form.BrandID).ID
            o.getSystemList()
            o.getTypeList()
          }
        } else {
          o.octopus.tips.error(data);
        }
      })
    },
    // 获取车系
    getSystemList() {
      let o = this
      this.octopus.request.api.post("/Octopus/Engine/List", {
        id: 1226,
        cellData: [
          {name: "ID"},	// ID
          {name: "Name"},	// Name
          {name: "ParentkeyValue", filterKey: '=', filterValue: this.ParentkeyValue},	// ParentkeyValue
        ]
      }, function(data) {
        if (data.status.code === 200) {
          o.SystemList = data.content.queryData
        } else {
          o.octopus.tips.error(data);
        }
      })
    },
    // 获取车型
    getTypeList() {
      let o = this
      this.octopus.request.api.post("/Octopus/Engine/List", {
        id: 1227,
        cellData: [
          {name: "ID"},	// ID
          {name: "Name"},	// Name
          {name: "ParentkeyValue"},	// ParentkeyValue
        ]
      }, function(data) {
        if (data.status.code === 200) {
          o.TypeList = data.content.queryData
        } else {
          o.octopus.tips.error(data);
        }
      })
    },

    // 
    hasDuplicates(arr, key) {
    const valueCount = {};
    for (const item of arr) {
        if (valueCount[item[key]]) {
            return true;
        }
        valueCount[item[key]] = 1;
    }
    return false;
}
  },
};
</script>
<style scoped>
.drawer_box {
  padding: 3rem 0.8rem 3rem 0;
  height: calc(100% - 5rem);
  display: flex;
  flex-direction: column;
}

.drawer_title {
  box-shadow: 0px 5px 5px rgb(230 228 228 / 30%);
  padding-bottom: 1rem;
}

.drawer_t {
  padding: 0 2.8rem;
  display: flex;
  justify-content: space-between;
}

.drawer_t_l {
  display: flex;
  align-items: center;
  font-size: 2rem;
  font-weight: bold;
}

.drawer_t_l_img {
  width: 2.8rem;
  margin-right: 1rem;
}

.drawer_t_r {
  width: 3rem;
  height: 3rem;
  cursor: pointer;
}

.button_box {
  margin-top: 1rem;
  padding: 0 3rem;
  display: flex;
}

.drawer_content {
  overflow-y: auto;
  margin-top: 1.5rem;
  height: calc(100vh - 11rem);
  padding: 0 3rem;
  width: 100%;
  padding-bottom: 1rem;
}

.drawer_content .title {
  font-size: 1.8rem;
  font-weight: bold;
}
.cat-info {
  margin: 2rem 0 2rem 2em;
}

.cat-info .delete-box {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background-color: #f88c52;
  position: relative;
  margin-right: 6px;
}
.cat-info .delete-box::before {
  position: absolute;
  content: '';
  width: 60%;
  height: 2px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  z-index: 1;
}

.form-item {
  display: flex;
  align-items: center;
  margin: 2rem 0 2rem 2em;
}
.form-item .label {
  width: 25%;
  display: flex;
  align-items: center;
  font-size: 1.6rem;
}

.form-item .input {
  width: 100%;
  height: 5rem;
  line-height: 5rem;
  padding: 0 2rem;
  border: 1px solid #F3E8E2;
  border-radius: 1rem;
}
>>>.form-item .el-select {
  width: 100%;
  height: 4.5rem;
  line-height: 5rem;
}
>>>.form-item .el-select .el-input {
  width: 100%;
  height: 4.5rem;
}

>>>.form-item .el-select .el-input__inner {
  cursor: pointer;
  padding-right: 35px;
  height: 100%;
  font-size: 1.8rem;
}
>>>.el-input__icon {
  line-height: 3.5rem;
}
.form-item .textarea {
  width: 100%;
  line-height: 5rem;
  padding: 0 2rem;
  border: 1px solid #F3E8E2;
  border-radius: 1rem;
}

.form-item .add-driver {
  height: 4.5rem;
  line-height: 4.5rem;
  border: 1px dashed #F87338;
  display: inline-block;
  padding: 0 1.5rem;
  cursor: pointer;
  border-radius: .5rem;
}

.form-item .add-driver i {
  color: #F87338;
  font-weight: 700;
  margin-right: .5rem;
}
.drawer_footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-right: 30px;
}

.drawer_footer .footer-btn {
  line-height: 4rem;
  background-color: #F78C51;
  color: #fff;
  margin: 0 1rem;
  padding: 0 3rem;
  border-radius: .5rem;
  cursor: pointer;
  border: none;
}
</style>